package com.lf.cloud.grab.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.lf.cloud.comm.webutils.GetWaterId;

public class FtpUtils {
	
	
	
	
	
	
	
	public static FTPClient loginFTP(){
		
		String loginurl = "101.201.68.159";
		String userName = "lexy";
		String userPwd = "Lexy9497";
		
		FTPClient ftpClient = new FTPClient();
		try {
			//连接FTP服务器
			ftpClient.connect(loginurl, 21);
			//登录FTP服务器
			ftpClient.login(userName, userPwd);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//验证FTP服务器是否登录成功
		int replyCode = ftpClient.getReplyCode();
		if(!FTPReply.isPositiveCompletion(replyCode)){
		 return null;
		}
		System.out.println("====>FTP 登录成功！");
		return ftpClient;
	}
	
	
	public static FTPClient loginOutFTP(FTPClient ftp){
		
		try {
			if(ftp!=null){
				ftp.logout();
				System.out.println("====>FTP 退出成功！");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	
	
	
	public static String UploadToFtp(String imgdir  , FTPClient ftpClient , ByteArrayInputStream byteArrayInputStream){
		
		String fileName = DateUtils.getSerialId()+".jpg";
		try {
//            ftpClient.setBufferSize(1024);
//            ftpClient.setControlEncoding("GBK");
            //设置文件类型（二进制）
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.storeFile(fileName, byteArrayInputStream);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return fileName;
	}
	public static String DownloadToLocal(String rootPath , String imgdir , byte[] fileArr  ){
		String fileName = GetWaterId.getWaterId()+".jpg";
		try {
			String fileDirPath = rootPath+File.separator+imgdir;
			File filedir = new File(fileDirPath);
			if(!filedir.exists()){
				filedir.mkdirs();
			}
			File file = new File(fileDirPath+File.separator+fileName);
			System.out.println("====> RealPath : "+fileDirPath+File.separator+fileName);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(fileArr);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return fileName;
		
	}

	
	public static void main(String[] args) {
		//UploadToFtp("ASC" , null);
		
		
	}
}
